package com.zhg.hx;

import javax.swing.*;
import java.io.File;

public class FormatFile {

    private IPrintPathInfo printPathInfo;

    public FormatFile(Class<? extends IPrintPathInfo> printPathInfoClass) throws IllegalAccessException, InstantiationException {
        this.printPathInfo = printPathInfoClass.newInstance();
    }

    public FormatFile() {
    }

    public void run(String dir) {
        if (dir == null || dir.length() <= 0) {
            dir = System.getProperty("user.dir");
        }
        System.out.println("[*]准备去除该文件夹中文件名的空格->" + dir);
        getFilesAndFormat(dir);
        JOptionPane.showMessageDialog(null, "修改完成！");
    }

    private void getFilesAndFormat(String path) {
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (File fileIndex : files) {
                    if (fileIndex.isDirectory()) {
                        getFilesAndFormat(fileIndex.getPath());
                    } else {
                        //操作文件操作
                        format(fileIndex);
                    }
                }
            }
        }
    }

    private void format(File file) {
        if (file.exists()) {
            String oldName = String.valueOf(file.getName());
            String newName = oldName.replaceAll(" ", "");
            String filePath = file.getPath();
            file.renameTo(new File(filePath.substring(0, filePath.lastIndexOf(File.separator)) + File.separator + newName));
            if (printPathInfo != null) {
                printPathInfo.printPath("[*]修改完成->:" + filePath);
            }
        }
    }
}